//
//  PlantsListViewController.m
//  PlotMate
//
//  Created by Brian Boyle on 27/03/2012.
//  Copyright (c) 2012 Brian Boyle. All rights reserved.
//

#import "PlantsListViewController.h"
#import "Plant.h"
#import "PlantDetailTableViewController.h"
#import "BrowsePlantViewController.h"
#import "UILabel+TextFont.h"
#import "PlantSet+CRUD.h"
#import "SavePlantSetTableViewController.h"

@interface PlantsListViewController()
@property (nonatomic, strong) MKNumberBadgeView *badgeView;
@end

@implementation PlantsListViewController
@synthesize context = _context;
@synthesize predicate = _predicate;
@synthesize sectionName = _sectionName;
@synthesize sortProperty = _sortProperty;
@synthesize plantCell = _plantCell;
@synthesize badgeView = _badgeView;

/*Set the NSFetchedResultsController with the results of the search request. The request params are passed into the class based on what we want
 to filter the plants by. e.g. Category, Seasons, Favourites*/
- (void)setupFetchedResultsController {
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Plant"];
    request.predicate = self.predicate; 
    NSSortDescriptor *sorter = [[NSSortDescriptor alloc] initWithKey:self.sortProperty ascending:YES];
    request.sortDescriptors = [NSArray arrayWithObject:sorter];
    self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:request managedObjectContext:self.context sectionNameKeyPath:self.sectionName cacheName:nil];
}


#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    //Initialise the plantSet badge
    self.badgeView = [[MKNumberBadgeView alloc] init];
    self.badgeView.hideWhenZero = YES;
}

- (void)viewDidUnload
{
    [self setPlantCell:nil];
    [super viewDidUnload];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self setupFetchedResultsController];
    
    //Set up the badge for plantSet count
    CGRect frame = CGRectMake(220, 3, 40, 35);
    self.badgeView.frame = frame;
    [self.navigationController.navigationBar addSubview:self.badgeView];
    self.badgeView.value =[PlantSet countPlantsPlantSetArray];
    self.badgeView.fillColor = [UIColor colorWithRed:0.4 green:0.522 blue:0.129 alpha:1];

}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.badgeView removeFromSuperview];
}


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
   return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Table view data source


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"plantCell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        [[NSBundle mainBundle] loadNibNamed:@"PlantListCell" owner:self options:nil];
        cell = _plantCell;
        self.plantCell = nil;
    }
    //Set the background image of the cell to be paper
    cell.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"list_bg.png"]];
    
    Plant *plant = [self.fetchedResultsController objectAtIndexPath:indexPath];
    
    UIImageView *thumbnail = (UIImageView *)[cell viewWithTag:1];
    thumbnail.image = [UIImage imageNamed:[plant.name stringByAppendingString:@"_S"]];
    
    UILabel *label = (UILabel *)[cell viewWithTag:2];
    label.text = plant.name;
    [label setSketchBlockFont];
    
    
    //Set the planting set and favoutire image indicators. Need to set them to nil if they dont exist in order to remove
    //any existing images that were there.
    UIImageView *set = (UIImageView *)[cell viewWithTag:3];
    if(plant.plantSets != nil && [plant.plantSets count] > 0){
        set.image = [UIImage imageNamed:@"list_set_indicator"];
    }else{
        set.image = nil;
    }
    
    UIImageView *favourite = (UIImageView *)[cell viewWithTag:4];
    if([plant.isFavourite isEqualToNumber:[NSNumber numberWithBool:YES]]){
        favourite.image = [UIImage imageNamed:@"list_favourite_indicator"];
    }else{
        favourite.image = nil;
    }
    
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 57;
}

-(void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath
{
    [self performSegueWithIdentifier:@"viewPlantDetail" sender:indexPath];
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self performSegueWithIdentifier:@"browsePlants" sender:indexPath];
    
}

-(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    return nil;
}

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
   
    if ([segue.identifier isEqualToString:@"viewPlantDetail"]) {
        Plant *plant = [self.fetchedResultsController objectAtIndexPath:sender];
        [segue.destinationViewController setPlant:plant];
    }else if([segue.identifier isEqualToString:@"browsePlants"]){
        Plant *plant = [self.fetchedResultsController objectAtIndexPath:sender];
        [segue.destinationViewController setIndexOfPlant:[self.fetchedResultsController.fetchedObjects indexOfObject:plant]];
        [segue.destinationViewController setPlantList:self.fetchedResultsController.fetchedObjects];
    }else if([segue.identifier isEqualToString:@"addToExistingPlantSetSegue"]){
        UINavigationController *navCon = (UINavigationController *)segue.destinationViewController;
        SavePlantSetTableViewController *savePlantSetVC = [navCon.viewControllers objectAtIndex:0];
        savePlantSetVC.addtoExistingPlantSet = YES;
    }
}


- (IBAction)saveSetPressed:(UIBarButtonItem *)sender 
{
    NSMutableArray *plantSetArray = [PlantSet getPlantSetFromNSUserDefaults];
    //Show an alert if there are no plants in the NSUserDefualts plant set array
    if(plantSetArray == nil || [plantSetArray count] == 0){
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Oops!" message:@"There is nothing to save! Please add a plant to the Planting Set first" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
    }else{
        NSString *addToExistingText;
        if ([[PlantSet getAllPlantSetsInContext:self.context] count] != 0) {
            addToExistingText = @"Add to existing Set";
        }
        UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:nil otherButtonTitles:@"Create new Set", addToExistingText, nil];
        
        //Show an action sheet asking the user if they want to create a new set or add to an exiting one
        actionSheet.actionSheetStyle = UIActionSheetStyleBlackOpaque;
        [actionSheet dismissWithClickedButtonIndex:0 animated:YES];
        [actionSheet showFromTabBar:self.tabBarController.tabBar];
    }
}

-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    //If we already have PlantSets in CoreData, then ask the user if they want to add to an existing one.
    //Otherwise just show one option to create a new planting set
    if ([[PlantSet getAllPlantSetsInContext:self.context] count] != 0) {
        switch (buttonIndex) {
            case 0:
                [self performSegueWithIdentifier:@"savePlantSetSegue" sender:self];
                break;
            case 1:
                [self performSegueWithIdentifier:@"addToExistingPlantSetSegue" sender:self];
                break;
            default:
                break;
        }
    }else{
        switch (buttonIndex) {
            case 0:
                [self performSegueWithIdentifier:@"savePlantSetSegue" sender:self];
                break;
                
            default:
                break;
        }
    }
}
@end
